<template>
  <page-header-wrapper :title="false">
    <a-card title="股东详情">
      <template #extra> <a-button type="primary" @click="handleEdit(detail)">编辑股东</a-button></template>
      <a-descriptions bordered title="" size="small">
        <a-descriptions-item label="股东名" :span="3"> {{ detail.name }} </a-descriptions-item>
        <a-descriptions-item label="联系电话" :span="3">{{ detail.phone }} </a-descriptions-item>
        <a-descriptions-item label="创建日期" :span="3"> {{ detail.createTime }} </a-descriptions-item>
        <a-descriptions-item label="初始股份" :span="3"> {{ detail.startStock }}元 </a-descriptions-item>
        <a-descriptions-item label="当前股份" :span="3"> {{ detail.curStock }}元 </a-descriptions-item>
        <a-descriptions-item label="股东状态" :span="3">
          <a-tag color="#82af6f" v-if="detail.status == 1">参股中</a-tag>
          <a-tag color="#abbac3" v-else>已停用</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3">{{ detail.memo }} </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card title="股东持股记录" style="margin-top: 24px">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.queryCondition" allow-clear placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" @click="handleRecordCreate()">新增记录</a-button>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :pagination="pagination"
        @change="handleTableChange"
        :columns="columns"
        :data-source="loadData"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.checkerStatus == 1">已审核</a-tag>
            <a-tag color="#abbac3" v-else>未审核</a-tag>
          </template>
        </span>
        <span slot="chgType" slot-scope="text, record">
          <template>
            {{ record.chgType == '1' ? '入股':record.chgType == '2'?'退股':'分红' }}
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleRecord(record)">进入</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <record-form
      ref="recordModal"
      :visible="recordVisible"
      :loading="recordConfirmLoading"
      :model="recordMdl"
      @cancel="handleRecordCancel"
      @ok="handleRecordOk"
    />
  </page-header-wrapper>
</template>

<script>
import { getStockUsingGET,addInStockUsingPOST, updateStockUsingPOST, getStockRecordListUsingGET ,exportStockRecordListUsingPOST} from '@/api/api/qiantaizhangwu.ts'
import CreateForm from './CreateForm'
import RecordForm from './RecordForm'
export default {
  name: 'CashierShareholderDetail',
  components: {
    CreateForm,
    RecordForm,
  },
  data() {
    return {
      mdl: null,
      visible: false,
      confirmLoading: false,
      recordMdl: null,
      recordVisible: false,
      recordConfirmLoading: false,
      pagination: {
        total: 0,
      },
      loading: false,
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      advanced: false,
      columns: [
        {
          title: '记账日期',
          dataIndex: 'operTime',
        },
        {
          title: '类型',
          dataIndex: 'chgType',
          scopedSlots: { customRender: 'chgType' },
        },
        {
          title: '金额(元)',
          dataIndex: 'chgValue',
        },
        {
          title: '股份(元)',
          dataIndex: 'curStock',
        },
        {
          title: '记账人',
          dataIndex: 'operatorName',
        },
        {
          title: '审核状态',
          dataIndex: 'status',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '备注',
          dataIndex: 'memo',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      detail: {},
      loadData: [],
    }
  },
  mounted() {
    this.getDetail()
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params){
      exportStockRecordListUsingPOST({...params}).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '股东持股记录列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    getDetail() {
      getStockUsingGET({ id: this.$route.params.id })
        .then((res) => {
          this.detail = res.data
        })
        .catch(() => {
          this.$message.error('获取详情失败,请联系管理员')
        })
    },
    handleSearch(val) {
      this.loading = true
      const params = {
        ...val,
      }
      getStockRecordListUsingGET(params)
        .then((res) => {
          this.loadData = res.data.list
          this.loading = false
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition:this.queryParam.queryCondition,
        status:this.queryParam.status,
        date:this.queryParam.date
      })
    },
    handleRecord(record) {
      this.$router.push({ path: `/cashier/shareholder/record/${record.id}` })
    },
    handleEdit(record) {
      this.mdl = { ...record }
      this.visible = true
    },
    handleOk() {
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          updateStockUsingPOST({ ...values })
            .then(() => {
              this.getDetail()
              this.visible = false
              this.confirmLoading = false
              this.$message.success('修改成功')
            })
            .catch(() => {
              this.confirmLoading = false
              this.$message.error('修改失败,请联系管理员')
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleRecordCreate() {
      this.recordMdl = {}
      this.recordVisible = true
    },
    handleRecordOk() {
      this.recordConfirmLoading = true
      const form1 = this.$refs.recordModal.form
      form1.validateFields((errors, values) => {
        if (!errors) {
          addInStockUsingPOST({ ...values,operTime:values.operTime,stockId: this.$route.params.id })
            .then(() => {
              this.handleSearch(this.queryParam)
              this.recordVisible = false
              this.recordConfirmLoading = false
              this.$message.success('操作成功')
            })
            .catch((error) => {
              this.recordConfirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
          this.recordConfirmLoading = false
        }
      })
    },
    handleRecordCancel() {
      this.recordVisible = false
      const form = this.$refs.recordModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
